# -*- coding: utf-8 -*-

from odoo import api, fields, models, _


class ZeroneBook(models.Model):
    _name = "zerone.book"
    _description = "Zerone Books"

    _inherit = ['image.mixin']

    image_1920 = fields.Binary(string="图书样例", store=True)
    name = fields.Char(string="图书名称", required=True)
    code = fields.Char(string="图书编号", copy=False, help="管理编号，用于快速定位图书")
    isbn = fields.Char(string="ISBN", copy=False)
    author = fields.Char(string="作者")
    pages = fields.Integer(string="页数")
    publish_date = fields.Date(string="出版时间")
    publisher = fields.Char(string="出版社")
    price = fields.Float(string="定价", digits=(7, 2))
    description = fields.Text(string="内容简介", help="""向借阅者描述本书的内容""")
    binding_type = fields.Selection(
        [("common", "普通"), ("hardcover", "精装")],
        string="装帧类型", index=True, default='common'
    )
    e_link = fields.Html(string="电子版连接")
    borrowed = fields.Boolean(string="是否被借阅", default=False)
    date_last_borrowed = fields.Datetime("最后被借阅时间", index=True, readonly=True)

    shelf_id = fields.Many2one('zerone.shelf', string='所在书架')
    tags_ids = fields.Many2many("zerone.tags", string="标签")

    @api.depends('isbn', 'name')
    def name_get(self):
        result = []
        for book in self:
            result.append((book.id, '%s(%s)' % (book.name, book.isbn)))
        return result

    # @api.model
    # def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
    #     return [
    #         {"id": 1, "code": "888", "name": "\u54c8\u54c8\u5417", "isbn": False, "author": False, "pages": 0,
    #          "price": 12455568.86, "publish_date": False, "publisher": "\u90ae\u7535", "binding_type": "hardcover",
    #          "borrowed": False},
    #         {"id": 2, "code": "004", "name": "\u8475\u82b1\u5b9d\u5178", "isbn": False, "author": False, "pages": 0,
    #          "price": 0.0, "publish_date": False, "publisher": "\u4eba\u6c11", "binding_type": "common",
    #          "borrowed": False},
    #         {"id": 3, "code": "005", "name": "\u5929\u9f99\u516b\u90e8", "isbn": False, "author": False, "pages": 0,
    #          "price": 0.0, "publish_date": False, "publisher": "\u90ae\u7535", "binding_type": "common",
    #          "borrowed": False}]
    #
    # def read(self, fields=None, load='_classic_read'):
    #     # import urllib.request
    #     # post_url = "http://10.200.251.52:8000/list/1"
    #     # request_param = bytes(urllib.parse.urlencode({"usernames": "1"}), encoding='utf8')
    #     # request = urllib.request.Request(post_url, data=request_param, method='GET')
    #     # a = urllib.request.urlopen(request)
    #     # print(a.read().decode())
    #
    #     import pymysql
    #     conn = pymysql.connect(host='112.126.88.195',port=3306,user='zshr',password='zshr',database='etc_issue_scgs')
    #     cursor = conn.cursor()
    #     sql = "select * from etc_user_info"
    #     row_count = cursor.execute(sql)
    #     print(row_count)
    #     print(cursor.fetchone())
    #     # 取出结果中所有数据
    #     for line in cursor.fetchall():
    #         print(line)
    #     cursor.close()
    #     conn.close()
    #     return [{"id": self.id, "name": "红楼梦", "code": "007", "image_1920": False,
    #              "__last_update": "2020-07-16 06:11:44", "shelf_id": False, "tags_ids": [],
    #              "display_name": "\u5929\u9f99\u516b\u90e8(False)"}]

    # @api.model
    # def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
    #     print('11111')
    #     return [{"publisher_count": 1, "pages": 0, "price": 0.0, "publisher": "\u4eba\u6c11"},
    #             {"publisher_count": 2, "pages": 0, "price": 88.86, "publisher": "\u90ae\u7535"}]


class ZeroneShelf(models.Model):
    _name = "zerone.shelf"
    _description = "Zerone Shelf"

    name = fields.Char("书架名称")
    capacity = fields.Integer("书架容量")
    capacity_rate = fields.Float(string="图书放置比", compute="_compute_rate")

    book_ids = fields.One2many('zerone.book', 'shelf_id', string="图书")

    @api.depends('capacity', 'book_ids')
    def _compute_rate(self):
        for record in self:
            if not record.capacity:
                record.capacity_rate = 0.0
            else:
                record.capacity_rate = 100.0 * len(record.book_ids) / record.capacity


class ZeroneTags(models.Model):
    _name = "zerone.tags"
    _description = "Zerone Tags"

    name = fields.Char("标签名称", size=10)
